/*
 * Copyright (C) 2019 @MTI Ltd.
 *
 */
package com.mti.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mti.component.ResponseCallBack;
import com.mti.component.ResponseCriteria;
import com.mti.component.ResponseInfo;
import com.mti.constant.ArmingTaskEnum;
import com.mti.dao.model.ArmingTaskRelationEntity;
import com.mti.dao.model.LfZdryArmingTaskEntity;
import com.mti.dao.model.SysDictEntity;
import com.mti.exception.BusinessException;
import com.mti.service.IArmingTaskRelationService;
import com.mti.service.ISpecialPersonArmingTaskService;
import com.mti.service.ISysDictService;
import com.mti.vo.ArmingTaskDetailVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ServerWebExchange;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @company 上海道枢信息科技-->
 * @anthor created by zhangmingxin
 * @date 2019/8/21
 * @change
 * @describe describe
 **/
@Api(value = "重点人员布防任务",description = "重点人员布防任务")
@RestController
@AllArgsConstructor
@RequestMapping(value = "/specialPersonArmingTask")
public class SpecialPersonArmingTaskController {
    private final ISpecialPersonArmingTaskService armingTaskService;
    private final IArmingTaskRelationService relationService;
    private final ISysDictService dictService;

    @ApiOperation(value = "根据任务ID获取任务")
    @RequestMapping(value = "", method = RequestMethod.GET)
    public ResponseInfo getById(@RequestParam(value = "taskId")@ApiParam(value = "任务Id",name = "taskId",required = true)String taskId){
        return new ResponseCallBack() {
            @Override
            public void execute(ResponseCriteria criteria, Object... obj) {
                criteria.addSingleResult(armingTaskService.getById(taskId));
            }
        }.sendRequest();
    }

    @ApiOperation(value = "获取任务列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public ResponseInfo getList(
            @RequestParam(value = "page")@ApiParam(value = "当前页",name = "page",required = true) Integer page,
            @RequestParam(value = "size")@ApiParam(value = "页大小",name = "size",required = true) Integer size,
            @RequestParam(value = "taskName",required = false)@ApiParam(value = "任务名称",name = "taskName")String taskName,
            @RequestParam(value = "specialLevel",required = false)@ApiParam(value = "重要程度",name = "specialLevel")Integer specialLevel,
            @RequestParam(value = "status",required = false)@ApiParam(value = "状态(1：未结束，2：已结束)",name = "status")Integer status,
            @RequestParam(value = "armingRange",required = false)@ApiParam(value = "布控范围",name = "armingRange")String armingRange,
            @RequestParam(value = "armingRangeId",required = false)@ApiParam(value = "布控范围Id",name = "armingRangeId")String armingRangeId,
            @RequestParam(value = "orgId",required = false)@ApiParam(value = "角色所属组织ID",name = "orgId")String orgId,
            @RequestParam(value = "oid",required = false)@ApiParam(value = "角色所属派出所ID",name = "oid")String oid,
            @RequestParam(value = "zrbm",required = false)@ApiParam(value = "责任部门",name = "zrbm")String zrbm,
            @RequestParam(value = "approveStatus",required = false)@ApiParam(value = "审批状态(多个使用英文逗号隔开)",name = "approveStatus")String approveStatus
    ){
        return new ResponseCallBack() {
            @Override
            public void execute(ResponseCriteria criteria, Object... obj) {
                IPage iPage = armingTaskService.getTaskList(page, size, taskName, specialLevel,status, armingRange,armingRangeId,orgId,oid,zrbm,approveStatus);
                criteria.addMapResult("record",iPage.getRecords());
                criteria.addMapResult("total",iPage.getTotal());
            }
        }.sendRequest();
    }

    @ApiOperation(value = "获取各区域派出所审批情况")
    @GetMapping(value = "/approveDetail")
    public ResponseInfo getApproveDetail(@RequestParam(value = "taskId")@ApiParam(value = "任务ID",name = "taskId") String taskId){
        return new ResponseCallBack() {
            @Override
            public void execute(ResponseCriteria criteria, Object... obj) {
                Optional.ofNullable(armingTaskService.getById(taskId)).ifPresent(item->{
                    String rangeIds = item.getArmingRangeId();
                    List<String> idList = new ArrayList<>(Arrays.asList(rangeIds.split(",")));
                    if(!idList.isEmpty()){
                       Set<String> excludeIds = dictService.list(new QueryWrapper<SysDictEntity>().lambda().eq(SysDictEntity::getType,"kp_ssxq_event")).parallelStream().map(SysDictEntity::getKey).collect(Collectors.toSet());
                       idList.removeIf(excludeIds::contains);
                       //查询有多少人已经审批完成
                        long approvedCount = relationService.count(new QueryWrapper<ArmingTaskRelationEntity>().lambda().eq(ArmingTaskRelationEntity::getAtId,taskId).eq(ArmingTaskRelationEntity::getApproveStatus,ArmingTaskEnum.FINISH_TYPE.ordinal()));
                        //查询有多少派出所已经上报
                        List<Map<String,Object>> reportedOrg = relationService.getReportedOrg(taskId);
                        Set<String> reportedSet = reportedOrg.parallelStream().filter(m->Long.parseLong(m.getOrDefault("reportedcount","").toString())>0).map(m->m.getOrDefault("reportorgid","").toString()).filter(s->!StringUtils.isEmpty(s)).collect(Collectors.toSet());
                        idList.removeIf(reportedSet::contains);
                        List<String> sysOrg = idList.isEmpty()?new ArrayList<>():dictService.getOrgByOid(idList);
                        criteria.addMapResult("approvedCount",approvedCount);
                        criteria.addMapResult("unreportedOrg",sysOrg);
                    }
                });
            }
        }.sendRequest();
    }

    @ApiOperation(value = "保存布防任务")
    @RequestMapping(value = "", method = RequestMethod.POST)
    public ResponseInfo save(@RequestBody LfZdryArmingTaskEntity entity){
        return new ResponseCallBack() {
            @Override
            public void execute(ResponseCriteria criteria, Object... obj) {
                armingTaskService.saveOrUpdate(entity);
            }
        }.sendRequest();
    }

//    @PutMapping
//    @ApiOperation(value = "更新布防任务")
//    public ResponseInfo update(@RequestBody LfZdryArmingTaskEntity entity){
//        return new ResponseCallBack() {
//            @Override
//            public void execute(ResponseCriteria criteria, Object... obj) {
//                armingTaskService.updateById(entity);
//            }
//        }.sendRequest();
//    }

    @ApiOperation(value = "根据布防信息获取重点人员")
    @RequestMapping(value = "/specialPerson", method = RequestMethod.POST)
    public ResponseInfo getSpecialPersonListByTaskInfo(@RequestBody ArmingTaskDetailVO taskDetailVO){
        return new ResponseCallBack() {
            @Override
            public void execute(ResponseCriteria criteria, Object... obj) {
                if(StringUtils.isEmpty(taskDetailVO.getTaskId()))
                    throw new BusinessException(500,"布防任务ID不能为空");
                IPage iPage = armingTaskService.getTaskSpecialPersons(taskDetailVO);
                criteria.addMapResult("record",iPage != null && iPage.getRecords() != null ? iPage.getRecords() : new ArrayList<>());
                criteria.addMapResult("total",iPage == null ? 0 : iPage.getTotal());
            }
        }.sendRequest();
    }

    @ApiOperation(value = "给布控任务下增加重点人员")
    @RequestMapping(value = "/addSpecialPersonToArmingTask", method = RequestMethod.GET)
    public ResponseInfo addSpecialPersonToArmingTask(
            ServerWebExchange exchange,
            @RequestParam(value = "taskId")@ApiParam(value = "任务ID",name = "taskId",required = true) String taskId,
            @RequestParam(value = "reportOrg")@ApiParam(value = "上报单位",name = "reportOrg",required = true) String reportOrg,
            @RequestParam(value = "specialPersonId")@ApiParam(value = "重点人员ID",name = "specialPersonId",required = true) String specialPersonId,
            @RequestParam(value = "isSpyAdd",required = false)@ApiParam(value = "是否情报中心新增(0:否,1:是)",name = "isSpyAdd") String isSpyAdd){
        return new ResponseCallBack() {
            @Override
            public void execute(ResponseCriteria criteria, Object... obj) {
                armingTaskService.addSpecialPersonToArmingTask(taskId,reportOrg, specialPersonId,isSpyAdd,exchange);
            }
        }.sendRequest();
    }

    @ApiOperation(value = "给布控任务下增加重点人员(多人)")
    @RequestMapping(value = "/addSpecialPersonListToArmingTask", method = RequestMethod.GET)
    public ResponseInfo addSpecialPersonListToArmingTask(
            ServerWebExchange exchange,
            @RequestParam(value = "taskId")@ApiParam(value = "任务ID",name = "taskId",required = true) String taskId,
            @RequestParam(value = "reportOrg")@ApiParam(value = "上报单位",name = "reportOrg",required = true) String reportOrg,
            @RequestParam(value = "isSpyAdd",required = false)@ApiParam(value = "是否情报中心新增(0:否,1:是)",name = "isSpyAdd") String isSpyAdd,
            @RequestParam(value = "specialPersonIdList")@ApiParam(value = "重点人员ID(多人)",name = "specialPersonIdList",required = true) String specialPersonIdList){
        return new ResponseCallBack() {
            @Override
            public void execute(ResponseCriteria criteria, Object... obj) {
                armingTaskService.addSpecialPersonListToArmingTask(taskId,reportOrg, specialPersonIdList,isSpyAdd,exchange);
            }
        }.sendRequest();
    }

    @ApiOperation(value = "删除布控任务下的重点人员")
    @RequestMapping(value = "/delSpecialPersonFromArmingTask", method = RequestMethod.GET)
    public ResponseInfo delSpecialPersonFromArmingTask(
            ServerWebExchange exchange,
            @RequestParam(value = "taskId")@ApiParam(value = "任务ID",name = "taskId",required = true) String taskId,
            @RequestParam(value = "reportOrg")@ApiParam(value = "上报单位",name = "reportOrg",required = true) String reportOrg,
            @RequestParam(value = "specialPersonId")@ApiParam(value = "重点人员ID",name = "specialPersonId",required = true) String specialPersonId
    ){
        return new ResponseCallBack() {
            @Override
            public void execute(ResponseCriteria criteria, Object... obj) {
                armingTaskService.delSpecialPersonFromArmingTask(taskId, specialPersonId,reportOrg,exchange);
            }
        }.sendRequest();
    }

    @ApiOperation(value = "启动或停止布防任务")
    @RequestMapping(value = "/armingTaskOperation", method = RequestMethod.GET)
    public ResponseInfo armingTaskOperation(@RequestParam(value = "operate")@ApiParam(value = "操作类型(1:启动，0：停止)",name = "operate",required = true) String operate,
                                            @RequestParam(value = "taskId")@ApiParam(value = "任务ID",name = "taskId",required = true) String taskId){
        return new ResponseCallBack() {
            @Override
            public void execute(ResponseCriteria criteria, Object... obj) {
                armingTaskService.armingTaskOperation(operate, taskId);
            }
        }.sendRequest();
    }

    @ApiOperation(value = "上报人员/申请撤销操作")
    @PostMapping(value = "/armingTaskReport")
    public ResponseInfo submitReport(
            ServerWebExchange exchange,
            @RequestParam(value = "taskId")@ApiParam(value = "任务ID",name = "taskId",required = true) String taskId,
            @RequestParam(value = "rid")@ApiParam(value = "人员关联ID(多个用‘,’隔开)",name = "rid",required = true) String rid,
            @RequestParam(value = "reportOrgId")@ApiParam(value = "上报单位",name = "reportOrgId",required = true) String reportOrgId,
            @RequestParam(value = "reportUserId")@ApiParam(value = "用户Id",name = "reportUserId",required = true) String reportUserId,
            @RequestParam(value = "reportUserName")@ApiParam(value = "用户名",name = "reportUserName",required = true) String reportUserName,
            @RequestParam(value = "type")@ApiParam(value = "操作类型(1：上报，2：申请撤销)",name = "type",required = true) String type,
            @RequestParam(value = "isSpyAdd")@ApiParam(value = "是否情报中心(0:否，1：是)",name = "isSpyAdd",required = true) String isSpyAdd
    ){
        return new ResponseCallBack() {
            @Override
            public void execute(ResponseCriteria criteria, Object... obj) {
                armingTaskService.armingTaskReport(taskId, reportOrgId, reportUserId, reportUserName,rid,type,isSpyAdd,exchange);
            }
        }.sendRequest();
    }

    @PostMapping(value = "/approve")
    @ApiOperation(value = "审核通过或退回")
    public ResponseInfo approveOrReject(
            ServerWebExchange exchange,
            @RequestParam(value = "rid")@ApiParam(value = "关联ID(可多个，用“,”分隔开)",name = "rid",required = true) String rid,
            @RequestParam(value = "status")@ApiParam(value = "状态(1:上报通过,2:上报退回,3:撤销通过,4:撤销退回)",name = "status",required = true) Integer status,
            @RequestParam(value = "description",required = false)@ApiParam(value = "审批说明",name = "description") String description){
        return new ResponseCallBack() {
            @Override
            public void execute(ResponseCriteria criteria, Object... obj) {
                relationService.approveArmingTask(rid,status,description,exchange);
            }
        }.sendRequest();
    }

    @ApiOperation(value = "获取重点人员审批记录")
    @GetMapping(value = "/relationInfo")
    public ResponseInfo getRelationInfo(@RequestParam(value = "rid")@ApiParam(value = "关联ID",name = "rid",required = true) String rid){
        return new ResponseCallBack() {
            @Override
            public void execute(ResponseCriteria criteria, Object... obj) {
                criteria.addSingleResult(relationService.getLogs(rid));
            }
        }.sendRequest();
    }
}
